<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        background-color: #666;
      }
    </style>
  </head>
  <body></body>
</html>

<script>
  //   环绕动画
  const canvas = document.createElement("canvas");
  canvas.width = 600;
  canvas.height = 600;
  document.body.append(canvas);
  const context = canvas.getContext("2d");

  let earthAngle = 0;
  let moonAngle = 0;
  //   画太阳
  function loop() {
    // 先把画笔存起
    context.save();

    // 画动画的关键，每次画之前都要清楚之前画的
    context.clearRect(0, 0, canvas.width, canvas.height);

    // 画太阳，x400，y300
    context.beginPath();
    context.arc(300, 300, 100, 0, Math.PI * 2);
    context.fillStyle = "#e3fa14";
    context.shadowColor = "#e3fa14";
    context.shadowBlur = 10;
    context.fill();
    context.closePath();

    // 画地球
    context.beginPath();
    // 改变原点先,让地球绕着原点旋转
    context.translate(300, 300);
    //   旋转角度
    context.rotate((Math.PI / 180) * (earthAngle += 0.3));
    context.translate(200, 0); // 这里不可以拿到月亮那个地方去确认中心点，这里是一层一层传递下去的。画完地球再画月亮
    context.arc(0, 0, 20, 0, 2 * Math.PI);
    context.fillStyle = "blue";
    context.shadowColor = "blue";
    context.shadowBlur = 10;
    context.fill();
    context.closePath();

    // 画月亮
    context.beginPath();
    context.rotate((Math.PI / 180) * moonAngle++);
    context.fillStyle = "#ccc";
    context.shadowColor = "#ccc";
    context.shadowBlur = 10;
    context.arc(35, 0, 8, 0, 2 * Math.PI);
    context.fill();
    context.closePath();

    // 恢复画笔
    context.restore();
    // requestAnimationFrame(loop);
  }

  requestAnimationFrame(loop);
</script>
